#!/usr/bin/env node

var fs = require('fs'),
    sys = require('sys'),
    exec = require('child_process').exec,
    jsPath = 'form-validator/',
    mainScript = jsPath + 'jquery.form-validator.js',
    mainMinifiedScript = jsPath + 'jquery.form-validator.min.js',
    newVersion = -1;

// Find out new version number
var versionParts = fs.readFileSync(mainScript, 'utf-8').split('@version ')[1].split('*/')[0].trim().split('.');
if(versionParts.length < 3) {
    // new version number is decided in code
    newVersion = versionParts.join('.');
}
else {
    // Increase the last number by one
    var newSubVersion = parseInt(versionParts.splice(versionParts.length-1, 1)[0]) + 1;
    newVersion = versionParts.join('.') + '.' + newSubVersion.toString();
}

console.log('Build version: '+newVersion);

// Get code docs
var documentation = fs.readFileSync(mainScript, 'utf-8').split('*/')[0]+'*/';
var docParts = documentation.split('@version ');
documentation = docParts[0] +'@version '+newVersion+'\n'+docParts[1].split('\n')[1];


/**
 * Create new minified version of a file and change version number
 * @param {String} sourceFile
 * @param {String} targetFile
 * @param {String} [bin]
 */
function buildFile(sourceFile, targetFile, bin) {
    var codeParts = fs.readFileSync(sourceFile, 'utf-8').split('@version '),
      lastCodeParts = codeParts[1].split("\n"),
      origCode = codeParts[0] + '@version '+newVersion+ "\n" + lastCodeParts.slice(1, lastCodeParts.length).join("\n") + "";

    fs.writeFileSync(sourceFile, origCode);
    fs.writeFileSync(targetFile, '');

    if(!bin)
      bin = 'uglifyjs %source% >> %target%';

    exec(bin.replace('%source%', sourceFile).replace('%target%', targetFile), function (error, stdout, stderr) {
        if(stdout)
            console.log('stdout: '+stdout);
        if(error)
            console.log('error: '+error);
        if(stderr)
            console.log('stderror: '+stderr);

        console.log('* '+targetFile);
    });
}

// Minify main script
buildFile(mainScript,  mainMinifiedScript);

// Put top documentation back into minified main script
fs.writeFileSync(mainMinifiedScript, documentation+"\n"+fs.readFileSync(mainMinifiedScript, 'utf-8'));

// Minify modules and language files
[jsPath, jsPath+'lang/'].forEach(function(path) {
  fs.readdirSync(path).forEach(function(fileName) {
    if(fileName.substr(-7) == '.dev.js') {
      var compressedFileName = path + fileName.substr(0, fileName.length - 6) + 'js';
      buildFile(path+fileName, compressedFileName);
    }
  });
});

// Minify default theme css
buildFile(jsPath+'theme-default.css', jsPath+'theme-default.min.css', 'sqwish %source%');